//
//  KjinfoBDResultController.m
//  PlayBall
//
//  Created by Sun Fanglei on 13-4-22.
//
//

#import "JddKjinfoBDResultController.h"
#import "SBJson.h"
#import "JddQuerySportOpenDetailOperation.h"
#import "FloatLayer.h"
@interface JddKjinfoBDResultController (){
    NSInteger _floatLayerIndex;
    FloatLayer *_layer;
}

@end

@implementation JddKjinfoBDResultController

@synthesize dateValue, pageSize, pageNo;
@synthesize datepick;
@synthesize datePickIndex;
@synthesize dataLabel;
@synthesize resultString;
@synthesize resultArray;
@synthesize ListTable;
@synthesize issueArray;

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddKjinfoBDResultController);

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return DELETE;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [resultArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 64.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    JddSportResultListItemCell *cell = [JddSportResultListItemCell getInstanceView];
    NSDictionary *dltNumber = [resultArray objectAtIndex:indexPath.row];
    cell.HTeam.text = [dltNumber objectForKey:@"HTeam"];
    cell.VTeam.text = [dltNumber objectForKey:@"VTeam"];
    cell.mno.text = [dltNumber objectForKey:@"MNo"];
    cell.rq.text = [NSString stringWithFormat:@"%@", [dltNumber objectForKey:@"Rq"]];
    cell.score.text = [dltNumber objectForKey:@"Score"];
    cell.content.text = [dltNumber objectForKey:@"NMm"];
    cell.cg.text = [JddCommonFunction getCGByKey:[dltNumber objectForKey:@"Cg"]];
    cell.tag = indexPath.row;
    cell.delegate = self;
    return cell;
}

-(void)initPages
{
    pageNo = 0;
    pageSize = 10;
}

-(void)startOperation{
    if ([resultArray count] < 10) {
        pageNo = 0;
        [resultArray removeAllObjects];
    }
    pageNo ++;
    JddQuerySportOpenDetailOperation *operation = [[JddQuerySportOpenDetailOperation alloc] init];
    operation.DateTime = dateValue;
    operation.actionCode = @"312";
    operation.delegate = self;
    operation.pageNo = pageNo;
    operation.pageSize = pageSize;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    
}
#pragma mark  需要注意的地方
-(void)QuerySportOpenDetailOperationResult:(NSData *)result{
    if (result) {
        SBJsonParser *parser = [[SBJsonParser alloc] init];
        resultString = [JddDataParser parseSportLotteryIssueResult:result];
        NSDictionary *dict = [parser objectWithString:resultString];
        for (id d in [dict objectForKey:@"item"]) {
            [resultArray addObject:d];
        }
        if ([issueArray count] <1) {
            issueArray = [dict objectForKey:@"Issues"];
        }
        [ListTable reloadData];
        NSDictionary *issueDict = [issueArray objectAtIndex:datePickIndex];
        dataLabel.text = [issueDict objectForKey:@"Name"];
    }
    [self finishReloadingData];
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:BD_RESULT_TITLE];
        customLab.textAlignment = NSTextAlignmentCenter;

        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
        
        
//    //self.navigationItem.hidesBackButton = YES;
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,0)];
    ListTable.tableFooterView = v;
    [self.ListTable setSeparatorColor:SeparatorLineColor];
    if (IOS7) {
        [self.ListTable setSeparatorInset:UIEdgeInsetsZero];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"OpenInfo-BDDetail"];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"OpenInfo-BDDetail"];

    [self initPages];
    
    resultArray = [[NSMutableArray alloc] init];
    [ListTable reloadData];
    datePickIndex = 0;
    dateValue = @"0";
    [self startOperation];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setDatepick:nil];
    [self setListTable:nil];
    [self setDataLabel:nil];
    [super viewDidUnload];
}

- (void)setLotteryContent:(NSInteger)index{
    
    _floatLayerIndex = index;
    [self selectMatch:[[issueArray objectAtIndex:index] objectForKey:@"Name"]];
}

- (IBAction)selectDate:(id)sender {
    if ([issueArray count] < 1) {
        return;
    }
    
    //需要判断是不是要显示
    NSArray *playMethod = [[NSArray alloc] init];
    for (NSDictionary *dict in issueArray) {
        playMethod =  [playMethod arrayByAddingObject:[dict objectForKey:@"Name"]];
    }
    
    if (!_layer) {
        _layer = [[FloatLayer alloc] initWithFloatLayer:FloatLayerList withLayerCallBack:^(NSInteger index) {
            [self setLotteryContent:index];
        }];
    }
    
    [_layer loadFloatLayer:playMethod withIndex:_floatLayerIndex];
    /*
    CGRect rect = [[UIScreen mainScreen] bounds];
    rect.origin.x = (rect.size.width - 251) / 2.0;
    rect.origin.y = (rect.size.height - 139) / 2.0;
    rect.size.width = 251.0;
    rect.size.height = 139.0;
    methodPick = [JddComboBoxView getInstanceView];
    [methodPick setFrame:rect];
    methodPick.dataArray = [NSArray arrayWithArray:playMethod];
    methodPick.type = 1;
    methodPick.commitButton.hidden = YES;
    methodPick.commitLabel.hidden = NO;
    methodPick.commitLabel.text = @"请选择日期";
    methodPick.delegate = self;
    [methodPick show];
    */
}

-(void)selectMatch:(NSString *)res{
    [self initPages];
    [resultArray removeAllObjects];
    for (int i=0; i<[issueArray count]; i++) {
        NSDictionary *issueDict = [issueArray objectAtIndex:i];
        if ([res isEqualToString:[issueDict objectForKey:@"Name"]]) {
            datePickIndex = i;
            dateValue = [issueDict objectForKey:@"ID"];
            [self startOperation];
        }
    }
}


- (void)setFooterView {
    CGFloat height = MAX(ListTable.contentSize.height, ListTable.frame.size.height);
    if (_refreshFooterView && [_refreshFooterView superview]) {
        _refreshFooterView.frame = CGRectMake(0.0f,
                                              height,
                                              ListTable.frame.size.width,
                                              self.view.bounds.size.height);
    } else {
        _refreshFooterView = [[EGORefreshTableFooterView alloc] initWithFrame:
                              CGRectMake(0.0f, height,
                                         ListTable.frame.size.width, self.view.bounds.size.height)];
        _refreshFooterView.delegate = self;
        _refreshFooterView.mainTableHeight = ListTable.frame.size.height;
        [ListTable addSubview:_refreshFooterView];
    }
    
    if (_refreshFooterView) {
        [_refreshFooterView refreshLastUpdatedDate];
    }
}

- (void)removeFooterView {
    if (_refreshFooterView && [_refreshFooterView superview]) {
        [_refreshFooterView removeFromSuperview];
    }
    _refreshFooterView = nil;
}


#pragma mark -
#pragma mark method that should be called when the refreshing is finished

- (void)finishReloadingData {
	_reloading = NO;
    [_refreshFooterView egoRefreshScrollViewDataSourceDidFinishedLoading:ListTable];
    [self setFooterView];
    
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
   // [_refreshFooterView egoRefreshScrollViewDidScroll:scrollView];
    //小于十条加载没有效果
    if ([resultArray count]<10 ) {
        _refreshFooterView.hidden = YES;
    }else{
        _refreshFooterView.hidden = NO;
        [_refreshFooterView egoRefreshScrollViewDidScroll:scrollView];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if ([resultArray count]<10) {
        
    }else{
        [_refreshFooterView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}

#pragma mark -
#pragma mark EGORefreshTableDelegate Methods

- (void)egoRefreshTableDidTriggerRefresh:(EGORefreshPos)aRefreshPos {
    _reloading = YES;
    [self performSelector:@selector(startOperation) withObject:nil afterDelay:1];
}

- (BOOL)egoRefreshTableDataSourceIsLoading:(UIView*)view {
	return _reloading;
}

- (NSDate *)egoRefreshTableDataSourceLastUpdated:(UIView*)view {
	return [NSDate date];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
